
<template>
  <div style="margin-top:10px; display: flex; justify-content: center">
    <h3>账号登录</h3>
  </div>

  <!-- 登录方式切换 -->
  <div style="display: flex; justify-content: center; margin-bottom: 10px">
    <van-button
        :type="loginType === 'code' ? 'primary' : 'default'"
        size="small"
        @click="loginType = 'code'"      style="margin-right: 10px"
    >
      验证码登录
    </van-button>
    <van-button
        :type="loginType === 'password' ? 'primary' : 'default'"
        size="small"
        @click="loginType = 'password'"
    >
      密码登录
    </van-button>
  </div>

  <van-cell-group>
    <van-field v-model="phone" type="digit" label="手机号" placeholder="请输入手机号" />
    <van-cell-group
        v-if="loginType === 'password'">
      <van-field
          v-model="password"
          type="password"
          label="密码"
          placeholder="请输入密码"
      />
      <div style="display: flex; justify-content: right">
        <!-- 使用 click 事件进行导航 -->
        <span @click="goToResetPassword" style="font-size: 12px">忘记密码?</span>
      </div>
    </van-cell-group>
    <van-cell-group v-if="loginType === 'code'"  >
      <van-field
          v-model="code"
          type="digit"
          label="验证码"
          placeholder="请输入验证码"
      >
        <template #button>
          <van-button
              size="small"
              type="primary"
              :disabled="isCountingDown"
              @click="sendCode">{{ countdownText }}</van-button>
        </template>
      </van-field>
      <div style="display: flex; justify-content: right">
        <!-- 使用 click 事件进行导航 -->
        <span @click="enroll" style="font-size: 12px">没有账号？点击注册</span>
      </div>
    </van-cell-group>
  </van-cell-group>



  <div style="display: flex; justify-content: center;margin-top: 10px">
    <van-button
        size="normal"
        type="primary"        style="border-radius: 20px; width: 260px"
        @click="login">
      登录
    </van-button>
  </div>
  <div v-if="loginType === 'code'" style="display: flex; justify-content: center; margin-top: 10px;">
    <span style="font-size: 12px; color: #999;">
      首次验证码登录将自动注册账号
    </span>
  </div>
</template>


<script setup>import {ref, computed, onUnmounted} from 'vue'
import {showFailToast, showSuccessToast} from 'vant'
import {useUserStore} from "../stores/user.js"
import 'vant/lib/toast/style'
import router from "../router/router.js"
import { useRoute } from 'vue-router'
import axios from "../axios/axiosInstance.js"

let timer = null // 定时器
let userStore = useUserStore()


const isCountingDown = ref(false) // 是否正在倒计时
const countdown = ref(60) // 倒计时秒数

const route = useRoute();
const loginType = ref(route.query.loginType||'code') // 默认验证码登录
const phone = ref(userStore.userInfo.phone)
const password = ref('')
const code = ref()

// 验证手机号是否为11位
const isValidPhone = computed(() => {
  return phone.value && phone.value.length === 11
})

const countdownText = computed(() => {
  return isCountingDown.value ? `${countdown.value}秒后重新发送` : '发送验证码'
})

const sendCode = () => {
  // 验证手机号
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  // ✅ 使用你配置好的 axios 实例
  axios.post('/user/sendCode', {
    phone: phone.value
  }).then(ServerData => {
    if (ServerData.data.code === 0) {
      showSuccessToast("验证码发送成功")
      console.log(ServerData.data.data)
      startCountdown()
    } else {
      showFailToast("验证码发送失败")
    }
  }).catch(error => {
    console.log("请求发生异常", error);
    showFailToast("验证码发送失败,请稍后重试");
  })
}

const login=()=>{
  // 验证手机号
  if (!phone.value) {
    showFailToast('请输入手机号')
    return
  }

  if (!isValidPhone.value) {
    showFailToast('请输入正确的11位手机号')
    return
  }

  if (loginType.value === 'password') {
    if (!password.value) {
      showFailToast('请输入密码')
      return
    }
    // ✅ 使用你配置好的 axios 实例
    axios.get("/user/loginByPassword",{params:{
        phone: phone.value,
        password: password.value
      }
    }).then((ServerData)=>{
      if (ServerData.data.code === 0){
        userStore.userInfo=ServerData.data.data
        userStore.userInfo.saTokenInfo=ServerData.data.saTokenInfo
        showSuccessToast("登录成功")
        // 用户获取用户个人信息
        localStorage.setItem('userId', ServerData.data.data.user_id);
        localStorage.setItem('username', ServerData.data.data.username);
        router.push('/home')
      }else {
        showFailToast(ServerData.data.msg);
      }
    }).catch((error)=>{
      console.log("请求发生异常",error);
      showFailToast("登录失败,请稍后重试");
    })
  }

  if (loginType.value === 'code'){
    if (!code.value) {
      showFailToast('请输入验证码')
      return
    }
    // ✅ 使用你配置好的 axios 实例
    axios.get('/user/loginByCode', {
      params:{phone: phone.value,
        code: parseInt(code.value)
      }
    }).then(ServerData => {
      if (ServerData.data.code === 0) {
        showSuccessToast("登录成功")
        userStore.userInfo=ServerData.data.data
        userStore.userInfo.saTokenInfo=ServerData.data.saTokenInfo
        router.push('/home')
      }else if(ServerData.data.code === 2){
        console.log(ServerData.data.msg)
        showFailToast("该手机号未注册,已为您自动注册")
        setTimeout(()=>{
          showSuccessToast("一秒后为您跳转首页")
          router.push('/home')
        },1000)
      } else {
        showFailToast(ServerData.data.msg)
      }
    }).catch(error => {
      console.log("请求发生异常", error);
      showFailToast("登录失败,请稍后重试");
    })
  }
}

const enroll = () => {
  router.push('/enroll')
}

const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60

  timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      stopCountdown()
    }
  }, 1000)
}

const stopCountdown = () => {
  isCountingDown.value = false
  clearInterval(timer)
  timer = null
}

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

const goToResetPassword = () => {
  router.push('/resetPassword')
}
</script>
<style scoped></style>